package com.jz.yanshe.ui.fragment;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.jz.jd.rest.business.RestProxy;
import com.jz.jd.rest.exception.BusinessException;
import com.jz.jd.rest.response.BaseResponse;
import com.jz.jd.rest.response.ShoppingCarListResponse;

import org.greenrobot.eventbus.EventBus;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import com.jz.yanshe.base.BaseFragment;
import com.jz.yanshe.eventbus.FragmentTabEvent;
import com.jz.yanshe.ui.BuyActivity;
import com.jz.yanshe.util.ImageLoaderHelper;
import com.jz.yanshe.util.PreferencesHelper;
import jz.com.feierman.R;

/**
 * Created by Administrator on 2018/2/26.
 */

public class ShoppingBagFragment extends BaseFragment {

    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.tv_total_price)
    TextView tv_total_price;
    @BindView(R.id.btn_pay)
    TextView btn_pay;
    @BindView(R.id.check_all)
    CheckBox check_all;
    @BindView(R.id.center)
    LinearLayout center;
    @BindView(R.id.bottom)
    RelativeLayout bottom;

    List<ShoppingCarListResponse.ShoppingCar> list = new ArrayList<>();

    MyAdapter myAdapter = new MyAdapter();

    public static ShoppingBagFragment newInstance() {
        return new ShoppingBagFragment();
    }


    @Override
    protected int getLayoutResource() {
        return R.layout.fragment_shoppingbag;
    }

    @Override
    protected void initView() {
        recyclerView.setAdapter(myAdapter);
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        recyclerView.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) {
                super.onDraw(c, parent, state);
            }

            @Override
            public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
                super.getItemOffsets(outRect, view, parent, state);
                outRect.bottom = 15;
            }
        });
    }

    Context mContext;
    @Override
    public void onAttach(Context context) {
        mContext = context;
        super.onAttach(context);
    }

    @Override
    protected void initData() {
//        getCarList("1", "1", "20");
    }


    class MyAdapter extends RecyclerView.Adapter<MyAdapter.Holder> {


        @Override
        public Holder onCreateViewHolder(ViewGroup parent, int viewType) {
            Holder holder = new Holder(getLayoutInflater().inflate(R.layout.item_shoppingbag, parent, false));
            return holder;
        }

        @Override
        public void onBindViewHolder(final Holder holder, final int position) {
            if (list.get(position).select) {
                holder.checkbox.setChecked(true);
            } else {
                holder.checkbox.setChecked(false);
            }
            ImageLoaderHelper.getInstance().GlideImageLoader(mContext, list.get(position).goods_icon, holder.img_goods);
            holder.tv_goods_name.setText(list.get(position).goods_name);
            holder.tv_goods_num.setText(list.get(position).goods_num);
            holder.tv_size.setText(list.get(position).style_color + "     " + list.get(position).style_size + "码");
            holder.tv_price.setText("¥ " + list.get(position).goods_price);
            holder.btn_minus.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (Integer.valueOf(holder.tv_goods_num.getText().toString().trim()) > 1) {
                        holder.tv_goods_num.setText((Integer.valueOf(holder.tv_goods_num.getText().toString().trim()) - 1) + "");
                        list.get(position).goods_num = holder.tv_goods_num.getText().toString();
                        refreshBottom();
                    }
                }
            });
            holder.btn_plus.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    holder.tv_goods_num.setText((Integer.valueOf(holder.tv_goods_num.getText().toString().trim()) + 1) + "");
                    list.get(position).goods_num = holder.tv_goods_num.getText().toString();
                    refreshBottom();
                }
            });

            holder.checkbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    list.get(position).select = isChecked;
                    refreshBottom();
                    if (!isChecked) {
                        check_all.setChecked(false);
                    }
                }
            });

            holder.btnDelete.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    delItem(list.get(position).shopping_cart_id, position);
                }
            });

        }

        @Override
        public int getItemCount() {
            return list.size();
        }

        class Holder extends RecyclerView.ViewHolder {
            ImageView img_goods;
            TextView tv_size, tv_goods_name, tv_goods_num, tv_price, btn_minus, btn_plus;
            CheckBox checkbox;
            Button btnDelete;

            public Holder(View itemView) {
                super(itemView);
                img_goods = itemView.findViewById(R.id.img_goods);
                tv_size = itemView.findViewById(R.id.tv_size);
                tv_goods_name = itemView.findViewById(R.id.tv_goods_name);
                tv_goods_num = itemView.findViewById(R.id.tv_goods_num);
                tv_price = itemView.findViewById(R.id.tv_price);
                btn_minus = itemView.findViewById(R.id.btn_minus);
                btn_plus = itemView.findViewById(R.id.btn_plus);
                checkbox = itemView.findViewById(R.id.checkbox);
                btnDelete = itemView.findViewById(R.id.btnDelete);
            }
        }
    }

    private void getCarList(String token, String page, String pageSize) {
        RestProxy.getInstance().getShoppingCarList(token, page, pageSize, new Observer<ShoppingCarListResponse>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(ShoppingCarListResponse shoppingCarListResponse) {
                list.clear();
                list.addAll(shoppingCarListResponse.listM);
                if(list.size() == 0){
                    center.setVisibility(View.VISIBLE);
                    recyclerView.setVisibility(View.GONE);
                    bottom.setVisibility(View.GONE);
                }else{
                    center.setVisibility(View.GONE);
                    recyclerView.setVisibility(View.VISIBLE);
                    bottom.setVisibility(View.VISIBLE);
                }
                refreshBottom();
                myAdapter.notifyDataSetChanged();
            }

            @Override
            public void onError(Throwable e) {
                if (e instanceof BusinessException) {
                    EventBus.getDefault().post(new FragmentTabEvent("1"));
                    toLogin(((BusinessException) e).errorCode);
                }
            }

            @Override
            public void onComplete() {

            }
        });
    }


    private void refreshBottom() {
        int num = 0;
        double price = 0;

        for (int i = 0; i < list.size(); i++) {
            if (list.get(i).select) {
                num = num + Integer.valueOf(list.get(i).goods_num);
                System.out.println(Double.valueOf(list.get(i).goods_price) + "        Double.valueOf(list.get(i).goods_price)");
                System.out.println(Integer.valueOf(list.get(i).goods_num) + "        Integer.valueOf(list.get(i).goods_num)");
                price = price + Integer.valueOf(list.get(i).goods_num) * Double.valueOf(list.get(i).goods_price);
            }
        }
        tv_total_price.setText("¥ " +     String.format("%.2f",Double.valueOf(price)));
        btn_pay.setText("去支付(" + num + ")");
    }


    @OnClick(R.id.check_all)
    void check_all() {
        for (int i = 0; i < list.size(); i++) {
            list.get(i).select = check_all.isChecked();
        }
        myAdapter.notifyDataSetChanged();
    }

    @OnClick(R.id.btn_pay)
    void btn_pay() {
        List<ShoppingCarListResponse.ShoppingCar> selectList = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            if (list.get(i).select) {
                selectList.add(list.get(i));
            }
        }
        if (selectList.size() == 0) {
            Toast.makeText(getActivity(), "请选择商品", Toast.LENGTH_SHORT).show();
            return;
        }
        Bundle bundle = new Bundle();
        bundle.putSerializable("list", (Serializable) selectList);
        startActivity(BuyActivity.class, bundle);
    }

    @Override
    public void onResume() {
        super.onResume();
        getCarList(PreferencesHelper.getInstance().getString(getActivity(), "token"), "1", "200");
    }

    private void delItem(String shopping_cart_id, final int position) {
        RestProxy.getInstance().delShoppingBag(PreferencesHelper.getInstance().getString(getActivity(), "token")
                , shopping_cart_id, new Observer<BaseResponse>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(BaseResponse baseResponse) {
                        list.remove(position);
                        myAdapter.notifyDataSetChanged();
                        refreshBottom();
                    }

                    @Override
                    public void onError(Throwable e) {

                        if (e instanceof BusinessException) {
                            toLogin(((BusinessException) e).errorCode);
                        }
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    @Override
    public void onStop() {
        for (int i = 0; i < list.size(); i++) {
            updateShoppingBag(list.get(i).shopping_cart_id, list.get(i).goods_num, list.get(i).goods_style_id);
        }
        super.onStop();
    }

    private void updateShoppingBag(String shopping_cart_id, String goods_num, String goods_style_id) {
        RestProxy.getInstance().updateShoppingBag(PreferencesHelper.getInstance().getString(getActivity(), "token"), shopping_cart_id, goods_num, goods_style_id, new Observer<BaseResponse>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(BaseResponse baseResponse) {

            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {

            }
        });
    }

    @OnClick(R.id.btn_confirm)
    void btn_confirm(){
        EventBus.getDefault().post(new FragmentTabEvent("1"));
    }
}
